package com.weiyuwqj.controller.user;

import com.weiyuwqj.api.constant.Constants;
import com.weiyuwqj.api.constant.Message;
import com.weiyuwqj.api.exception.CrowdException;
import com.weiyuwqj.api.model.*;
import com.weiyuwqj.api.service.*;
import com.weiyuwqj.api.util.MD5;
import com.weiyuwqj.api.util.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import java.io.UnsupportedEncodingException;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.logging.Logger;

/**
 * Created by zhangyong on 2016/11/24.
 */
@Controller
public class UserSecurityController {
    private static Logger log = Logger.getLogger("UserSecurityController");

    @Autowired
    BasUserSecurityService userSecurityService;
    @Autowired
    BasUserService userService;
    @Autowired
    SysTempcodeService tempcodeService;
    @Autowired
    BusAccountBankService accountBankService;
    @Autowired
    BasUserInfoService userInfoService;

    /**
     * 查询个人信息
     * @return
     */
    @ResponseBody
    @RequestMapping("/user/security/information")
    public Object information(HttpServletRequest request){
       /* Integer userId=(Integer)request.getSession().getAttribute("userId");
        Integer id =userId;
        BasUser user=userService.selectByKey(id);
        if(user!=null){
            user.setPassword("");
            user.setSalt("");
            user.setMobile(StringUtils.getString(user.getMobile()));
        }

        BasUserSecurity security=userSecurityService.getOneByUserId(userId);
        Integer age=0;
        if(security != null){
            if(security.getRealnameStatus()==1){
//                age=StringUtils.IdNOToAge(security.getIdentifyCard());
                security.setRealname(StringUtils.getString(security.getRealname()));
                security.setIdentifyCard(StringUtils.getString(security.getIdentifyCard()));
                security.setAccountNumber(StringUtils.getString(security.getAccountNumber()));
                security.setUserNumber(StringUtils.getString(security.getUserNumber()));
                security.setPaymentPassword("");
            }
        }
        //查询银行卡信息
        BusAccountBank busAccountBank = accountBankService.getOneByUserId(userId);
        if(busAccountBank!=null){
            busAccountBank.setCardNo(StringUtils.getString(busAccountBank.getCardNo()));
        }
        int grade = 2;
        //查询用户信息
        BasUserInfo userInfo = userInfoService.getOneByUserId(userId);

        if(userInfo.getUserRiskType() != null){
            grade = grade + 1;
        }
        //安全星级

        if(security.getRealnameStatus() == 1){
            grade = grade + 2;
        }
        Map map=new HashMap();
        map.put("grade",grade);
        map.put("userInfo",userInfo);
        map.put("user",user);
        map.put("age",age);
        map.put("security",security);
        map.put("bank",busAccountBank);
        return map;*/
       return null;
    }

    /**
     * 安全中心页面
     * @param request
     * @return
     */
    @RequestMapping("/user/security")
    public Object security(HttpServletRequest request){
        Integer userId=(Integer)request.getSession().getAttribute("userId");
        Integer id=userId;
        //查询个人信息
        BasUser user=userService.selectByKey(id);
        if(user!=null){
            user.setPassword("");
            user.setSalt("");
            user.setMobile(StringUtils.getString(user.getMobile()));
        }
        //查询安全信息
        BasUserSecurity security=userSecurityService.getOneByUserId(userId);
        if(security != null){
            if(security.getRealnameStatus()==1){
                security.setRealname(StringUtils.getString(security.getRealname()));
                security.setIdentifyCard(StringUtils.getString(security.getIdentifyCard()));
                security.setPaymentPassword("");

            }
        }
        //查询银行卡信息
        BusAccountBank busAccountBank = accountBankService.getOneByUserId(userId);
        if(busAccountBank!=null){
            busAccountBank.setCardNo(StringUtils.getString(busAccountBank.getCardNo()));
        }

        int grade = 2;
        //查询用户信息
        BasUserInfo userInfo = userInfoService.getOneByUserId(userId);
/*        if(userInfo.getUserRiskType() !=null){
            grade = grade + 1;
        }*/
        //安全星级

        if(security.getRealnameStatus() == 1){
            grade = grade + 2;
        }
        request.getSession().setAttribute("grade",grade);
        request.getSession().setAttribute("user",user);
        request.getSession().setAttribute("userInfo",userInfo);
        request.getSession().setAttribute("security",security);
        request.getSession().setAttribute("bank",busAccountBank);
        return "main/user/setting";
    }

    /**
     * 实名认证
     * @return
     */
    @ResponseBody
    @RequestMapping("/user/security/doRealname")
    public Object doRealname(HttpServletRequest request,String realName,String identityNum,String payPassWord,String payPasswordCheck,String email){
/*        Integer userId=(Integer)request.getSession().getAttribute("userId");
        Map map=userSecurityService.webRealname(userId, realName, identityNum, payPassWord, payPasswordCheck, email);
        if(map!=null&&!map.get("code").equals("000000")){
            map.put("messageText",map.get("msg").toString());
            return map;
        }*/
        return Message.OK;
    }
    /**
     * 实名认证跳转
     */
    @RequestMapping("/user/security/realname")
    public Object realName(){
        return "/main/user/realName";
    }

    /**
     * 绑卡
     */
    @ResponseBody
    @RequestMapping("/user/security/tieOnCard")
    public Object tieOnCard(HttpServletRequest request,String bankName,String cardNo,String bankMobile,String mobileCode,String bankCode){
        /*Long validPhoneExpiredTime = (Long) request.getSession().getAttribute("validPhoneExpiredTime");
        String validPhoneCode=request.getSession().getAttribute("validPhoneCode").toString();

        //发送短信
        Date now = new Date();
        long between = (now.getTime() - validPhoneExpiredTime) / 1000;

        if (!(validPhoneCode.equals(mobileCode))) {
            throw new CrowdException("user.register.randomCode.error");
        }
        if (between > Constants.VALIDATETIME) {
            throw new CrowdException("user.register.randomCode.timeout");
        }
        SysTempcode tempcode=tempcodeService.getByMobileAndCode(bankMobile, validPhoneCode);
        if(tempcode==null){
            throw new CrowdException("user.register.randomCode.error");
        }

        Integer userId=(Integer)request.getSession().getAttribute("userId");

        Map map=userSecurityService.webTieOnCard(userId, bankName, cardNo, bankMobile, bankCode);
        if(map!=null&&!map.get("code").equals("000000")){
            log.info("map----------"+map);
            map.put("messageText",map.get("msg"));
            return map;
        }*/
        return Message.OK;
    }

    /**
     * 解绑
     */
    @ResponseBody
    @RequestMapping("/user/security/cardUnbund")
    public Object cardUnbund(HttpServletRequest request,String payPassword){
/*        Integer userId=(Integer)request.getSession().getAttribute("userId");
        return userSecurityService.webCardUnbund(userId,payPassword);*/
return null;
    }


    /**
     * 修改绑定手机号码
     * @param request
     * @param mobile
     * @param inputRandomCode
     * @return
     */
    @ResponseBody
    @RequestMapping("/user/modifyMobile")
    public Object modifyMobile(HttpServletRequest request,String mobile,String inputRandomCode){
        Object obj = request.getSession().getAttribute("validPhoneCode");
        Object timeObj =request.getSession().getAttribute("validPhoneExpiredTime");
        String validPhoneCode="";
        if(obj ==null || timeObj==null){
            throw new CrowdException("auto.sms_not_exists");
        }
        Long validPhoneExpiredTime = (Long) timeObj;
        validPhoneCode=obj.toString();
        Integer userId=(Integer)request.getSession().getAttribute("userId");
        BasUser user=userService.getUserByMobile(mobile);
        //判断新手机是否存在
        if (null !=user) {
            throw new CrowdException("user.register.mobile_already_exists");
        }
        //判断验证码与手机是否匹配
        SysTempcode tempcode=tempcodeService.getByMobileAndCode(mobile, validPhoneCode);
        if(tempcode==null){
            throw new CrowdException("user.register.randomCode.error");
        }
        //短信校验
        Date now = new Date();
        long between = (now.getTime() - validPhoneExpiredTime) / 1000;

        if (!(validPhoneCode.equals(inputRandomCode))) {
            throw new CrowdException("user.register.randomCode.error");
        }
        if (between > Constants.VALIDATETIME) {
            throw new CrowdException("user.register.randomCode.timeout");
        }
        //修改手机号码
        //userService.modifyMobile(mobile,userId);
        return Message.OK;
    }

    /**
     * 修改密码
     * @param request
     * @param oldPassword 旧密码
     * @param newPassword 新密码
     * @return
     */
    @ResponseBody
    @RequestMapping("/user/modifyPassword")
    public Object modifyPassword(HttpServletRequest request,String oldPassword,String newPassword) {
        Integer userId = (Integer) request.getSession().getAttribute("userId");
        Integer id = userId;
        BasUser user = userService.selectByKey(id);
        try {
            oldPassword = MD5.toMD5(oldPassword + user.getSalt());
            newPassword = MD5.toMD5(newPassword + user.getSalt());
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        if (!oldPassword.equals(user.getPassword())) {
            throw new CrowdException("modify_password.old_password_error");
        }
        userService.modifyPassword(user.getMobile(), newPassword);
        return Message.OK;
    }

    /**
     * 修改支付密码
     * @param request
     * @param oldPayPassword
     * @param newPayPassword
     * @return
     */
    @ResponseBody
    @RequestMapping("/user/modifyPayPassword")
    public Object modifyPayPassword(HttpServletRequest request,String oldPayPassword,String newPayPassword,String mobileCode,String idCard) {
        Integer userId = (Integer) request.getSession().getAttribute("userId");
        BasUser user = userService.selectByKey(userId);

        Long validPhoneExpiredTime = (Long) request.getSession().getAttribute("validPhoneExpiredTime");
        String validPhoneCode=request.getSession().getAttribute("validPhoneCode").toString();

        //发送短信
        Date now = new Date();
        long between = (now.getTime() - validPhoneExpiredTime) / 1000;
        //短信验证
        if (!(validPhoneCode.equals(mobileCode))) {
            throw new CrowdException("user.register.randomCode.error");
        }
        if (between > Constants.VALIDATETIME) {
            throw new CrowdException("user.register.randomCode.timeout");
        }
        SysTempcode tempcode=tempcodeService.getByMobileAndCode(user.getMobile(), validPhoneCode);
        if(tempcode==null){
            throw new CrowdException("user.register.randomCode.error");
        }
        //修改交易密码
       // userSecurityService.modifyPayPassword(userId,oldPayPassword,newPayPassword,idCard);
        return Message.OK;
    }




}
